package com.example.sneakerappforme1105;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.sneakerappforme1105.bean.BackendGoods;
import com.example.sneakerappforme1105.bean.Goods;
import com.example.sneakerappforme1105.bean.Order;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.GoodsDao;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PaymentActivity extends AppCompatActivity {

    private GoodsDao goodsDao;
    private Long mUserId;
    private Long mCartId;
    private Long orderId;
    private String TAG = "PaymentAct";
    private LinearLayout paymentSuccessContainer;
    private ImageView paymentSuccessImage;
    private ImageView paymentfail;
    private Button viewOrderButton;
    private WebView webView;
    private TextView tv_title3;
    boolean isFirst=false;
    long savedOrderId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG,"启动");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        tv_title3 = findViewById(R.id.tv_title3);
        tv_title3.setText("支付详情");
        paymentSuccessImage = findViewById(R.id.iv_payment_success);
        paymentfail = findViewById(R.id.iv_payment_fail);


        findViewById(R.id.iv_back3).setOnClickListener(view -> {
            Intent resultIntent = new Intent();
            resultIntent.putExtra("orderId", orderId); // 将 orderId 放入 Intent
            setResult(RESULT_OK, resultIntent);       // 设置结果和数据
            finish();
        });
        goodsDao = MainApplication.getInstance().getAppDatabase().goodsDao();
        webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        mUserId = getIntent().getLongExtra("userId",0L);
        mCartId = getIntent().getLongExtra("cartId",0L);
        orderId = getIntent().getLongExtra("orderId",0L);
        SharedPreferences sharedPreferences = getSharedPreferences("saveOrderId", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        // 检查 SharedPreferences 中是否已有值
        savedOrderId = sharedPreferences.getLong("orderId", 0L);
        long savedUserId = sharedPreferences.getLong("userId", 0L);
        long savedCartId = sharedPreferences.getLong("cartId", 0L);

        if (savedOrderId != orderId) {  // orderId是现在传来的值
            Log.d(TAG,"不相等");
            isFirst = true;
            savedOrderId = orderId;
            editor.putBoolean("isFirst", true);  // 保存首次访问状态
            editor.putLong("orderId", savedOrderId);
        }else{
            Log.d(TAG,"相等");
            isFirst = sharedPreferences.getBoolean("isFirst", false);  // 加载已有状态
            isFirst = false;
        }




        if (savedUserId != mUserId) {
            Log.d(TAG,"订单号不相等");
            savedUserId = mUserId;
            editor.putLong("userId", savedUserId);
        }

        if (savedCartId != mCartId) {

            savedCartId = mCartId;
            editor.putLong("cartId", savedCartId);
        }

        // 应用更改
        editor.apply();

        // 获取传递过来的支付表单
        String paymentHtml = getIntent().getStringExtra("paymentHtml");
        Log.d("Payment",paymentHtml);
        // 加载支付表单
        webView.loadDataWithBaseURL(null, paymentHtml, "text/html", "UTF-8", null);


        // 初始化支付成功的图片和按钮
        paymentSuccessContainer = findViewById(R.id.payment_success_container);
        paymentSuccessImage = findViewById(R.id.iv_payment_success);
        viewOrderButton = findViewById(R.id.btn_view_order);
        viewOrderButton.setOnClickListener(view -> {

            Log.d(TAG,"用户Id和购物车id"+mUserId);
            Intent intent = new Intent(PaymentActivity.this,ShowOrderActivity.class);
            intent.putExtra("userId",mUserId);

            startActivity(intent);
        });

        isFirst=false;


    }


    @Override
    protected void onResume() {
        super.onResume();
        // 更新商品库存 请求后台
        Log.d(TAG,"重启Payment");
        onPaymentSuccess();
        SharedPreferences sharedPreferences = getSharedPreferences("saveOrderId", MODE_PRIVATE);
        orderId = getIntent().getLongExtra("orderId", 0L);
        Log.d(TAG, "从 Intent 获取的订单号为：" + orderId);
        if (orderId == 0L) {
            sharedPreferences = getSharedPreferences("saveOrderId", MODE_PRIVATE);
            long orderId = sharedPreferences.getLong("orderId", 0L);
            Log.d(TAG, "从 SharedPreferences 获取的订单号为：" + orderId);
        }


        Log.d(TAG,""+isFirst);
        if(isFirst) {  // 首次访问
            pollPaymentStatus(orderId, paymentSuccessContainer, webView);
            // 重置 isFirst 状态为 false
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("isFirst", false);
            editor.apply();
        }


        Log.d(TAG,"订单号为"+orderId);

        isFirst=true;
    }

    private void onPaymentSuccess() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"goods/all")  // get请求
                .build();
        System.out.println("刷新商品库存");

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("请求图片数据失败!");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if(response.isSuccessful()){
                    System.out.println("请求图片数据!");
                    String jsonResponse = response.body().string();
                    Gson gson = new Gson();



                    JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);


                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    Type listType = new TypeToken<List<BackendGoods>>() {}.getType();
                    List<BackendGoods> backendGoodsList = gson.fromJson(dataArray, listType);

                    runOnUiThread(()->{
                        for(BackendGoods g: backendGoodsList){
                            Goods goods = goodsDao.queryGoodsByGoodsId(g.getGoodsId());
                            goods.setCapcity(g.getCapcity());
                            goodsDao.updateGoods(goods);    // 更新库存
                        }
                    });



                }
            }
        });
    }


    private void pollPaymentStatus(Long orderId, LinearLayout paymentSuccessContainer, WebView webView) {

        OkHttpClient client = new OkHttpClient();


        Request request = new Request.Builder()
                        .url(NetConst.HTTP_PREFIX + "order/query/" + orderId)
                        .build();

        client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e("PaymentActivity", "Failed to fetch order status", e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String jsonResponse = response.body().string(); // 有状态码
                            Gson gson = new Gson();
                            JsonObject jsonObject = gson.fromJson(jsonResponse, JsonObject.class);

                            // 尝试获取 "data" 字段
                            JsonElement dataElement = jsonObject.get("data");
                            System.out.println(jsonResponse);

                            // 检查 "data" 是否为空或不存在
                            if (dataElement == null || dataElement.isJsonNull() ) {
                                Log.d("OrderParsing", "未支付或 data 为空 "+orderId);
                                // 处理未支付的情况
                            } else {
                                JsonObject dataObject = dataElement.getAsJsonObject(); // 转换为 JsonObject
                                mUserId = dataObject.get("userId").getAsLong();   // 获取 userId
                                Log.d("UserId", "用户 ID: " + mUserId);
                                Order order = gson.fromJson(dataElement, Order.class);
                                if ("paid".equals(order.getStatus())) {
                                    // 如果订单状态为已支付
                                    runOnUiThread(() -> {
                                        paymentSuccessContainer.setVisibility(View.VISIBLE);
                                        webView.setVisibility(View.GONE);

                                    });
                                }else{
                                    // 支付失败
                                    runOnUiThread(() -> {
                                        paymentSuccessContainer.setVisibility(View.VISIBLE);

                                        webView.setVisibility(View.GONE);
                                        paymentSuccessImage.setVisibility(View.GONE);
                                        paymentfail.setVisibility(View.VISIBLE);
                                        viewOrderButton.setText("支付失败，立马去支付");
                                    });
                                }
                            }
                        }
                    }
                });

            }
        };



